﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace XLETL.Common
{
  /// <summary>
  /// Class contains methods for Encrypting/Decrypting string
  /// </summary>
  public sealed class Cryptography
  {
    public static string EnDeCrypt(string data, bool isEncrypt) 
    { 
      byte[] u8_Salt = new byte[] { 0x26, 0x19, 0x81, 0x4E, 0xA0, 0x6D, 0x95, 0x34, 0x26, 0x75, 0x64, 0x05, 0xF6 };
      PasswordDeriveBytes passDerv = new PasswordDeriveBytes("1pa$$word0", u8_Salt);
      using (Rijndael rijndael = Rijndael.Create())
      {
        rijndael.Key = passDerv.GetBytes(32);
        rijndael.IV = passDerv.GetBytes(16);
        
        using (MemoryStream memStream = new MemoryStream())
        {
          using (ICryptoTransform cryptoTran = (isEncrypt) ? rijndael.CreateEncryptor() : rijndael.CreateDecryptor())
          {
            using (CryptoStream cryptoStream = new CryptoStream(memStream, cryptoTran, CryptoStreamMode.Write))
            {
              byte[] u8_Data;
              if (isEncrypt)
              {
                u8_Data = Encoding.Unicode.GetBytes(data);
              }
              else
              {
                u8_Data = Convert.FromBase64String(data);
              }

              try
              {
                cryptoStream.Write(u8_Data, 0, u8_Data.Length);
                cryptoStream.Close();
                if (isEncrypt) return Convert.ToBase64String(memStream.ToArray());
                else return Encoding.Unicode.GetString(memStream.ToArray());
              }
              catch { return null; }
            }
          }
        }
      }
    }
  }
}

